#include "smartBuffer.h"

using namespace std;

namespace smartBuffer
{
    

SmartBuffer::SmartBuffer()
{
    m_buf = new char[m_cap];
}

SmartBuffer::SmartBuffer(size_t size)
{
    m_buf = new char[size];
    m_size = size;
    m_cap = size;
}

SmartBuffer::SmartBuffer(const SmartBuffer & src)
{
    m_cap = src.m_cap;
    m_size = src.m_size;
    m_buf = new char[m_cap];
    memcpy(m_buf, src.m_buf, m_size);
}

SmartBuffer::SmartBuffer(SmartBuffer && src)
{
    m_size = src.m_size;
    m_cap = src.m_cap;
    m_buf = src.m_buf;
    src.m_isUse = false;
}

SmartBuffer::~SmartBuffer()
{
    if(m_isUse == true) delete m_buf;
}

void SmartBuffer::add(char * src, size_t size)
{
    if(size <= (m_cap - m_size))
    {
        memcpy(m_buf + m_size, src, size);
        m_size += size;
    }
    else
    {
        m_cap += size;
        char * newbuf = new char[m_cap];
        memcpy(newbuf, m_buf, m_size);
        memcpy(newbuf + m_size, src, size);
        m_size += size;
        delete m_buf;
        m_buf = newbuf;
    }
}

char * SmartBuffer::getPtr()
{
    return m_buf;
}

SmartBuffer & SmartBuffer::operator = (const SmartBuffer & src)
{
    m_cap = src.m_cap;
    m_size = src.m_size;
    delete m_buf;
    m_buf = nullptr;
    m_buf = new char[m_cap];
    memcpy(m_buf, src.m_buf, m_size);
    return *this;
}

SmartBuffer & SmartBuffer::operator = (SmartBuffer && src)
{
    m_size = src.m_size;
    m_cap = src.m_cap;
    delete m_buf;
    m_buf = nullptr;
    m_buf = src.m_buf;
    src.m_isUse = false;
    return *this;
}

size_t SmartBuffer::size()
{
    return m_size;
}


}
